#include "personal_info_logic.h"
#include <QBuffer>
#include <QDebug>
#include <QFileDialog>
#include <QMessageBox>
#include "PptpMessage.h"
#include "UserSession.h"
#include"globals.h"
PersonalInfoLogic::PersonalInfoLogic(PersonalInfoUI *ui, QObject *parent)
    : QObject(parent), ui(ui)
{
    connect(ui, &PersonalInfoUI::avatarLabelClicked, this, &PersonalInfoLogic::onAvatarLabelClicked);
    connect(ui->getSaveButton(), &QPushButton::clicked, this, &PersonalInfoLogic::onSaveClicked);
    connect(ui->getAccountSecurityButton(),
            &QPushButton::clicked,
            this,
            &PersonalInfoLogic::onAccountSecurityClicked);
    getUserInfo();
    getAvatar();
}

PersonalInfoLogic::~PersonalInfoLogic() {}

void PersonalInfoLogic::onSaveClicked()
{
    QString nickname = ui->getNicknameEdit()->text();
    QString gender = ui->getGenderEdit()->text();
    QString email = ui->getEmailEdit()->text();
    QString signature = ui->getSignatureEdit()->text();
    int userId = UserSession::getInstance().getUserId();

    QJsonObject parameters;
    parameters["personName"] = nickname;
    parameters["sex"] = gender;
    parameters["email"] = email;
    parameters["sign"] = signature;
    parameters["userId"] = userId;

    qDebug() << "保存的用户信息" << parameters;

    requestMessage.clear();
    requestMessage.setParameters(parameters);
    requestMessage.setPath("user/editUserInfo");
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &PersonalInfoLogic::onSaveResponse);
}
void PersonalInfoLogic::onSaveResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    qDebug() << responseParameters;

    QString message = responseParameters.value("message").toString();
    bool success = responseParameters.value("isOK").toBool();

    if (success)
    {
        QMessageBox::information(nullptr, "保存成功", message);
        uplogic->getUserInfo();

    }
    else
    {
        QMessageBox::warning(nullptr, "保存失败", message);
    }
}
void PersonalInfoLogic::getUserInfo()
{
    PptpMessage requestMessage;
    QJsonObject parameters;

    requestMessage.clear();
    requestMessage.setPath("user/getUserInfo");
    int userId = UserSession::getInstance().getUserId(); // 从 Usersession 获取 userId
    parameters["userId"] = userId;
    requestMessage.setParameters(parameters);
    qDebug() << parameters;
    qDebug() << "id;" << userId;
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &PersonalInfoLogic::onUserInfoResponse);
}
void PersonalInfoLogic::onUserInfoResponse(PptpMessage responseMessage)
{
    QJsonObject responseParameters = responseMessage.getParameters();
    qDebug() << responseParameters;

    QString personName = responseParameters.value("personName").toString();
    QString sex = responseParameters.value("sex").toString();
   // QString birthday = responseParameters.value("birthday").toString();
    QString email = responseParameters.value("email").toString();
    QString sign = responseParameters.value("sign").toString();
    ui->getNicknameEdit()->setText(personName);
    ui->getGenderEdit()->setText(sex);
    //ui->getBirthdayEdit()->setText(birthday);
    ui->getEmailEdit()->setText(email);
    ui->getSignatureEdit()->setText(sign);
}
void PersonalInfoLogic::onAvatarLabelClicked()
{
    qDebug() << "Avatar label clicked!";
    QString fileName = QFileDialog::getOpenFileName(nullptr,
                                                    tr("选择头像"),
                                                    "",
                                                    tr("Images (*.png *.jpg *.jpeg *.bmp)"));

    // 如果用户选择了文件
    if (!fileName.isEmpty())
    {
        QPixmap newAvatar(fileName);

        // 检查图片是否加载成功
        if (!newAvatar.isNull())
        {
            // 将新头像设置到UI中
            ui->avatarLabel->setPixmap(
                newAvatar.scaled(100,
                                 100,
                                 Qt::KeepAspectRatio,
                                 Qt::SmoothTransformation)); // 头像大小可根据需求调整
            qDebug() << "New avatar set from file:" << fileName;
            // 转换为QImage
            QImage image = newAvatar.toImage();
            // 创建一个QByteArray对象用于存储图像数据
            QByteArray avatar;
            QBuffer buffer(&avatar);
            buffer.open(QIODevice::WriteOnly);
            // 保存QImage到QByteArray
            bool success = image.save(&buffer, "PNG"); // 你可以根据需要更改格式，比如"JPG"
            if (success)
            {
                qDebug() << "Image successfully converted to QByteArray.";
                // 现在你可以使用byteArray变量了，例如存储或发送
                PptpMessage requestMessage;
                requestMessage.addFile("avatar", avatar);
                requestMessage.setPath("user/setAvatar");
                QJsonObject job;
                job["userId"] = UserSession::getInstance().getUserId();
                requestMessage.setParameters(job);
                pptpclient.pptpConnect(IP,
                                       PORT,
                                       requestMessage,
                                       this,
                                       &PersonalInfoLogic::setAvatarResponse);
            }
            else
            {
                qDebug() << "Failed to convert image to QByteArray.";
            }
        }
        else
        {
            qDebug() << "Failed to load image from file:" << fileName;
        }
    }
    else
    {
        qDebug() << "No file selected!";
    }
}

void PersonalInfoLogic::setAvatarResponse(PptpMessage responseMessage) {
    QJsonObject responseParameters = responseMessage.getParameters();
    qDebug() << responseParameters;
    uplogic->getAvatar();
}

void PersonalInfoLogic::getAvatar()
{
    qDebug() << "Fetching user avatar...";

    PptpMessage requestMessage;
    QJsonObject parameters;
    parameters["userId"] = UserSession::getInstance().getUserId(); // 获取当前用户的ID
    requestMessage.clear();
    requestMessage.setParameters(parameters);
    requestMessage.setPath("user/getAvatar");
    pptpclient.pptpConnect(IP, PORT, requestMessage, this, &PersonalInfoLogic::onGetAvatarResponse);
}

void PersonalInfoLogic::onGetAvatarResponse(PptpMessage responseMessage)
{
    qDebug() << "Avatar fetched from server.";

    // 从响应消息中获取头像数据
    QHash<QString, QByteArray> files = responseMessage.getFiles();

    // 假设avatar文件存在于返回的数据中
    QByteArray responseData = files.value("avatar");

    if (responseData.isEmpty())
    {
        qDebug() << "No avatar data found in the response.";
        return;
    }

    // 将字节数组转换为QPixmap
    QPixmap avatar;
    bool success = avatar.loadFromData(responseData, "PNG"); // 根据服务器返回的格式指定类型

    if (success)
    {
        // 将头像设置到UI中
        ui->avatarLabel->setPixmap(
            avatar.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation));
        qDebug() << "User avatar set successfully.";
    }
    else
    {
        qDebug() << "Failed to load avatar from response data.";
    }
}

void PersonalInfoLogic::onAccountSecurityClicked()
{
    qDebug() << "Account security clicked";
}
